package cn.ubeta.b2c.widget;

import android.app.Activity;
import android.app.DownloadManager;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.View;

import cn.ubeta.b2c.R;
import cn.ubeta.b2c.utils.Constants;
import cn.ubeta.b2c.utils.FileUtils;

import java.io.File;
import java.lang.reflect.Field;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import static android.os.Environment.getExternalStorageDirectory;

public class DownLoadProgressDialog extends ProgressDialog {
    private Activity context;
    private String version;
    private String apkUrl;
    private final int QUERY = 1;
    private DownloadManager downloadManager;
    private File downFile;
    private DownloadManager.Query query;
    private long downloadId;

    private BroadcastReceiver mDownloadReceiver;
    ScheduledExecutorService scheduledExecutorService;
    Future<?> future;

    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {

                case QUERY:
                    query = new DownloadManager.Query().setFilterById(downloadId);
                    Cursor cursor = downloadManager.query(query);

                    if (cursor != null && cursor.moveToFirst()) {
                        //此处直接查询文件大小
                        long downSize = cursor.getLong(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
                        //获取文件下载总大小
                        long fileTotalSize = cursor.getLong(cursor.getColumnIndex(
                                DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
                        cursor.close();
                        if (fileTotalSize != 0) {
                            int percentage = (int) (downSize * 100 / fileTotalSize);

                            setProgress(percentage);
                        }
                        //终止轮询task
                        if (fileTotalSize == downSize)
                            future.cancel(true);
                    }
            }
            return true;
        }
    });
    BroadcastReceiver downloadCompleteReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            long completeDownloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);

            if (completeDownloadId == downloadId) {
                setProgress(100);
                if (downFile != null) {
                    if(getButton(BUTTON_POSITIVE)!=null){
                        getButton(BUTTON_POSITIVE).setVisibility(View.VISIBLE);
                    }
                    startInstallApk(context, downFile);
                }
                //cancel();
            }
        }
    };

    public DownLoadProgressDialog(final Activity context, String title, String apkUrl) {
        this(context, title, "new", apkUrl, false, true);
    }

    public DownLoadProgressDialog(final Activity context, String title, String version, String apkUrl, boolean cancleable, boolean cancleOnTouchOutSide) {
        super(context);
        this.context = context;
        this.version = version;
        this.apkUrl = apkUrl;
        setTitle(title);
        setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        setCanceledOnTouchOutside(cancleOnTouchOutSide);
        setCancelable(cancleable);
        setButton(BUTTON_POSITIVE, "点击安装", (dialog, which) -> {
            try {
                Field field = dialog.getClass().getSuperclass().getSuperclass().getSuperclass()
                        .getDeclaredField("mShowing");//父类需取到Dialog才能关闭点击按钮调用dismiss
                field.setAccessible(true);
                field.set(dialog, false);
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            }
            if(downFile!=null){
                startInstallApk(context, downFile);
            }
        });
        setProgress(0);
    }

    @Override
    public void show() {
        super.show();
        getButton(BUTTON_POSITIVE).setVisibility(View.GONE);
        startDownloadApk(version, apkUrl);
    }

    /**
     * 启动apk下载
     */
    private void startDownloadApk(String version, String apkUrl) {
        final String fileName = "jd_meishi_" + version + ".apk";
        String localFileName = getExternalStorageDirectory().getPath() + "/" + Environment.DIRECTORY_DOWNLOADS + "/" + fileName;
        File file = new File(localFileName);
        // 检查是否已经下载
        if (file.exists()) {
            //startInstallApk(this, file);
            //return;
            FileUtils.deleteFile(localFileName);
        }
        downFile = new File(localFileName);
        downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
        Uri uri = Uri.parse(apkUrl);
        DownloadManager.Request request = new DownloadManager.Request(uri);
        request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);
        request.setTitle(context.getString(R.string.app_name));
        request.setDescription("正在下载...");
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_ONLY_COMPLETION);
        request.setMimeType(Constants.MIMETYPE_APK);

        downloadId = downloadManager.enqueue(request);
        DownloadManager.Query query = new DownloadManager.Query().setFilterById(downloadId);
        context.registerReceiver(downloadCompleteReceiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
        scheduledExecutorService = Executors.newScheduledThreadPool(1);
        //每过10ms通知handler去查询下载状态
        future = scheduledExecutorService.scheduleAtFixedRate(() -> {
            Message msg = mHandler.obtainMessage();
            msg.what = QUERY;
            mHandler.sendMessage(msg);
        }, 0, 10, TimeUnit.MILLISECONDS);
    }

    @Override
    public void cancel() {
        if (future != null && !future.isCancelled())
            future.cancel(true);

        if (scheduledExecutorService != null &&
                !scheduledExecutorService.isShutdown())
            scheduledExecutorService.shutdown();
        if (downloadCompleteReceiver != null) {
            context.unregisterReceiver(downloadCompleteReceiver);
        }
        context = null;
        super.cancel();
    }

    /**
     * 启动安装
     *
     * @param file
     */
    private static void startInstallApk(Context context, File file) {
        Intent apkIntent = new Intent(Intent.ACTION_VIEW);
        apkIntent.setDataAndType(Uri.fromFile(file), Constants.MIMETYPE_APK);
        apkIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(apkIntent);
    }

}
